package com.atguigu.chapter07.state;

import com.atguigu.bean.WaterSensor;
import com.atguigu.util.AtguiguUtil;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.Comparator;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/20 11:40
 */
public class Flink05_State_KV_List {
    
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        env
            .socketTextStream("hadoop162", 9999)
            .map(value -> {
                String[] datas = value.split(",");
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
                
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                
                private ListState<Integer> top3State;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    top3State = getRuntimeContext()
                        .getListState(new ListStateDescriptor<Integer>("top3State", Integer.class));
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    top3State.add(value.getVc());
    
                    List<Integer> list = AtguiguUtil.toList(top3State.get());
//                    list.sort((o1, o2) -> o2.compareTo(o1));
                    list.sort(Comparator.reverseOrder());  // 对list集合中数据原地排序
    
                    if (list.size() > 3) { // 如果长度大于3(其实是4), 删除最后一个
                        list.remove(list.size() - 1);
                    }
    
                    top3State.update(list);  // 更新状态
    
                    out.collect(ctx.getCurrentKey() + "  " + list.toString());
    
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}

